import BASE_URL from '@/utils/env.js';
 
export const request = (options) => {
  let url = options.url;
  let method = (options.method || 'GET').toUpperCase();
  let hideLoading = options.hideLoading || false;

  // 获取用户令牌
  let token = uni.getStorageSync('token');

  // 设置请求头（统一使用 Authorization: Bearer <token>）
  const bearerToken = token ? (String(token).startsWith('Bearer ') ? String(token) : `Bearer ${String(token)}`) : '';
  const header = {
    Authorization: bearerToken,
    ...options.header
  };

  // 根据请求方法决定使用 params（GET）还是 data（POST/PUT）
  let requestData;
  if (method === 'GET' || method === 'HEAD' || method === 'DELETE') {
    requestData = options.params || {};
  } else {
    requestData = options.data || {};
  }

  if (!hideLoading) {
    uni.showLoading({ title: '加载中' });
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      method: method,
      data: requestData, // 关键：必须写 data: ...
      header: header,
      success: (res) => {
        if (!hideLoading) uni.hideLoading();

        if (res.statusCode === 200) {
          const { code, msg, message } = res.data || {};
          console.log(code);
          console.log(code);
          if (code === 0) {
            resolve(res.data);
          } else if (code === 406) {
            uni.showToast({ title: msg || message || '登录已过期', icon: 'none' });
            uni.clearStorage();
            uni.navigateTo({ url: '/pages/index/login' });
          } else if (code === 401) {
            uni.showToast({ title: msg || message || '未登录', icon: 'none' });
            uni.clearStorage();
            uni.navigateTo({ url: '/pages/index/login' });
          } else {
            uni.showModal({
              title: '提示',
              content: msg || message || '请求失败',
              showCancel: false,
              confirmText: '我知道了'
            });
          }
        } else {
          uni.showToast({
            title: res.data?.message || '请求异常',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        if (!hideLoading) uni.hideLoading();
        uni.showToast({ title: '网络错误，请检查连接', icon: 'none' });
        reject(err);
      }
    });
  });
};